//save,get
const express=require('express');
const router=express.Router();
const passport=require("passport");
const isExist=require('../../config/publicFun').isExist;
const Follow=require('../../models/Follow');


//$route  Post api/follows/doFollow
//@desc   return state
//@access private 关注
router.post("/saveFollow",passport.authenticate("jwt",{session:false}),(req,res)=>{
    let option={
        user:req.user.id,
        follow:req.body.follow,
    };
    
    let follow=new Follow(option);
    follow.save((err)=>{
        if(err){
            res.json({"ok":1});
        }
        else{
            res.json({"ok":0});
        }
    })   
})

//$route  Post api/follows/canserFollow
//@desc   return state
//@access private 取关
router.post("/canserFollow",passport.authenticate("jwt",{session:false}),(req,res)=>{
    Follow.deleteOne({user:req.user.id,follow:req.body.follow},err=>{
        if(err){
            res.json({"ok":1});
        }
        else{
            res.json({"ok":0});
        }
   });
})

//$route  Post api/follows/getUserFollows
//@desc   return follows
//@access public 获得单个用户的关注列表
router.post('/getUserFollows',(req,res)=>{
    let user=req.body.user;
    Follow.find({'user':user})
    .sort({'date':-1})
    .populate([{'path':'follow','select':'name avatar'}])
    .exec((err,follows)=>{
        if(err){
            res.json({'ok':1,'data':[]});
        }
        else{
            res.json({'ok':0,'data':follows});
        }
    })
})


//$route  Post api/follows/getUserFollowCount
//@desc   return follows
//@access public 获得单个用户的关注量
router.post('/getUserFollowCount',(req,res)=>{
    let user=req.body.user;
    Follow.count({'user':user})
    .then((count)=>{
        res.json({'ok':0,'data':count});
    })
})

//$route  Post api/follows/getUserFansCount
//@desc   return follows
//@access public 获得单个用户的粉丝量
router.post('/getUserFansCount',(req,res)=>{
    let user=req.body.user;
    Follow.count({'follow':user})
    .then((count)=>{
        res.json({'ok':0,'data':count});
    })
})

//$route  Post api/follows/getIsFollow
//@desc   return follows
//@access private 判断是否关注过
router.post('/getIsFollow',passport.authenticate("jwt",{session:false}),(req,res)=>{
    let option={
        user:req.user.id,
        follow:req.body.follow,
    };
    isExist(option,Follow,doc=>{
        if(doc.length==0){
            res.send('未关注');
        }
        else{
            res.send('已关注');
        }
    })
})



module.exports=router;